#!/bin/bash
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

check_hardware() {
  scanimage -L > /dev/null || exit 1
  if [ `uname` = "Linux" ]; then
    SERIAL_DEVICE=/dev/ttyUSB0
    stty -F $SERIAL_DEVICE 9600
  else
    SERIAL_DEVICE=/dev/cu.usbserial-FTC8534M
  fi
  [ -e $SERIAL_DEVICE ] || exit 1
}

get_barcode() {
  echo "Please type or wand barcode"
  read barcode
  if [ -z $barcode ]; then
    barcode="default"
  fi
  barcode=${barcode}_$(date +%s)
  DIR=/var/tmp/playground/$barcode
  mkdir -p $DIR && cd $DIR
}

scan() {
  cat $SERIAL_DEVICE | scanimage --batch=%06d.pnm --batch-prompt \
    --page-height 355 -y 355 \
    --source "ADF Duplex" --mode Color --resolution 300 $@
}

HERE=`pwd`
check_hardware
get_barcode
$HERE/viewer.py $DIR &
scan 

